//
//  LSHttpTool.m
//  LearningSystemMEE
//
//  Created by heyong on 16/3/30.
//  Copyright © 2016年 bjttsx. All rights reserved.
//

#import "LSHttpTool.h"
#import "AFNetworking.h"
static BOOL checkNetWork;
@implementation LSHttpTool




+(void)Post:(NSString *)URLString parameters:(id )parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    
    NSString *postStr=DEF_PERSISTENT_GET_OBJECT(@"loginuserPost");
    if(postStr!=nil &&![postStr isEqualToString:@""]){
        [parameters setObject:postStr forKey:@"username"];
        [manager.requestSerializer setValue:postStr forHTTPHeaderField:@"username"];
    }
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"app_type"];
    
    [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
        
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSString *code=[dic objectForKey:@"code"];
        NSLog(@"%@--%@",task.currentRequest.URL.absoluteString,dic[@"msg"]);

        if([code isEqualToString:@"0"]){
            if([dic[@"msg"] isEqualToString:@"项目id为空"]){
                
            }else{
             [LSUtility showToastWithMessage:dic[@"msg"] inView:[UIApplication sharedApplication].keyWindow Andtime:1.5];
            }
     
        }
        success(dic);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
        NSLog(@"error:%@",error);
    }];
}

+(void)PostExit:(NSString *)URLString parameters:(id )parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //声明请求的数据是json
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //设置请求时间
    manager.requestSerializer.timeoutInterval = 30;
    //申明返回的数据是json
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"app_type"];

    [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        success(dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
//      [SVProgressHUD showErrorWithStatus:@"请求超时"];
        NSLog(@"error:%@",error);
    }];
}


#pragma mark- 网络监测
+(void)checkNetWork:(successBlock)success
{
    
    
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态发生改变的时候调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                checkNetWork=YES;
                 success(@"wifi");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                checkNetWork=YES;
                 success(@"wwan");
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
            {
                checkNetWork=NO;
                success(@"0");
              
            }
                break;
            case AFNetworkReachabilityStatusUnknown:
                checkNetWork=NO;
                success(@"0");
                break;
        }
    }];
    // 开始监控
    [mgr startMonitoring];
}



//接口测试
+(void)PostCheckIP:(NSString *)URLString parameters:(id )parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //声明请求的数据是json
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //设置请求时间
    manager.requestSerializer.timeoutInterval = 6;
    //申明返回的数据是json
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"app_type"];
    NSString *postStr=DEF_PERSISTENT_GET_OBJECT(@"loginuserPost");
    if(postStr!=nil &&![postStr isEqualToString:@""]){
        [parameters setObject:postStr forKey:@"username"];
        [manager.requestSerializer setValue:postStr forHTTPHeaderField:@"username"];
    }
    
    [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        success(dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        //        [SVProgressHUD showErrorWithStatus:@"请求超时"];
        NSLog(@"error:%@",error);
    }];
}

#pragma mark- 网络监测
+(void)checkNetWorkForView:(UIView *)view
{
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        // 当网络状态发生改变的时候调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                checkNetWork=YES;
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                checkNetWork=YES;
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
            {
                checkNetWork=NO;
                [LSUtility showToastWithMessage:@"网络连接已断开" inView:view Andtime:1.];
                NSLog(@"无网络连接");
            }
                break;
                
            case AFNetworkReachabilityStatusUnknown:
                checkNetWork=NO;
                //[MBProgressHUD showError:@"未知网络"];
                NSLog(@"未知网络");
                break;
        }
    }];
    // 开始监控
    [mgr startMonitoring];
}


/*
 *  附件上传 + 图片名
 **/
+ (void)upload:(NSString *)URLString parameters:(NSMutableDictionary *)parameters andFileName:(NSString *)fileName progress:(void (^)(id))progress success:(void (^)(id))success failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
   
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"app_type"];
    NSString *postStr=DEF_PERSISTENT_GET_OBJECT(@"loginuserPost");
    if(postStr!=nil &&![postStr isEqualToString:@""]){
        [parameters setObject:postStr forKey:@"username"];
        [manager.requestSerializer setValue:postStr forHTTPHeaderField:@"username"];
    }
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSString *path= DEF_FILE_PATH;
        
        NSString *filePath=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",fileName]];
        
        UIImage *image=[UIImage imageWithContentsOfFile:filePath];
        
        NSData *data=UIImageJPEGRepresentation(image, 0.1);
        
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(uploadProgress);
                
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"上传成功：%@,msg:%@",responseObject,responseObject[@"msg"]);
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败：%@",error);
        failure(error);
    }];
    
}

/**
 *  AFN3.0 下载
 */
+ (void)downLoad:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"app_type"];
    NSString *postStr=DEF_PERSISTENT_GET_OBJECT(@"loginuserPost");
    if(postStr!=nil &&![postStr isEqualToString:@""]){
        [manager.requestSerializer setValue:postStr forHTTPHeaderField:@"username"];
    }
    NSURL *url = [NSURL URLWithString:URLString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        NSLog(@"%lf",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        
        return [NSURL URLWithString:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        NSLog(@"%@--%@",response,filePath);
        
    }];
    
    //开始启动任务
    [task resume];
    
}



/*
 *  附件上传 + 图片名 更改头像
 **/
+ (void)upload:(NSString *)URLString parameters:(NSMutableDictionary *)parameters andFileName:(NSString *)fileName andImage:(UIImage *)image progress:(void (^)(id))progress success:(void (^)(id))success failure:(void (^)(NSError *))failure {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", nil]];
    
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"app_type"];
    
    NSString *postStr=DEF_PERSISTENT_GET_OBJECT(@"loginuserPost");
    if(postStr!=nil &&![postStr isEqualToString:@""]){
        [parameters setObject:postStr forKey:@"username"];
        [manager.requestSerializer setValue:postStr forHTTPHeaderField:@"username"];
    }
    
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *data=UIImageJPEGRepresentation(image, 0.1);
        
        [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(uploadProgress);
        //        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"msg:%@",responseObject[@"msg"]);
        
        NSString *code=responseObject[@"code"];
        if([code isEqualToString:@"1"]){
            NSLog(@"上传成功：%@,msg:%@",responseObject,responseObject[@"msg"]);
            success(responseObject);
        }else{
            NSLog(@"上传失败：%@",responseObject[@"msg"]);
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"上传失败：%@",error);
        failure(error);
    }];
}


+ (BOOL)reachability
{
    [self checkNetWork:^(NSString *status) {
        
    }];
    return checkNetWork;
}

- (void)dealloc
{
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
}

@end
